import { Injectable, Inject } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, CanActivateChild } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { TokenService, DA_SERVICE_TOKEN } from "@delon/auth";
import { Constant } from "@core/constant";
import { MenuService, Menu } from "@delon/theme";



/**
 * 路由守卫服务
 */
@Injectable()
export class AuthGuardService implements CanActivate, CanActivateChild {


    constructor(
        private menu: MenuService,
        private router: Router,
        private cnt: Constant,
        @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService
    ) {

    }

    /**
     * 保护需要登录权限的路由
     * @param route
     * @param state 即将被路由到的url
     */
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url;
        if (url === "/403" || url === "/404" || url === "/500") {
            return true;
        }
        if (url === "/lock") {
            // 未登录不能进入锁屏
            if (!this.checkLogin(url)) {
                return false;
            }
            return true;
        }
        let ret = this.checkLogin(url) && this.checkLock();
        if (ret) {
            if (!this.checkMenuAuth(url) && url != '/home') {
                // console.log(`${url}要跳转`)
                // this.router.navigate(['/403']);
                // return false;
              return true;
            }
        }
        return ret;
    }

    /**
     * 保护需要登录权限的子路由
     * @param route
     * @param state
     */
    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.canActivate(route, state);
    }

    checkLogin(url: string): boolean {
        const isLogined = this.tokenService.get().token ? true : false;
        if (isLogined) { return true; }
        // 未登录, 重定向到登录页
        console.log(`[${url}]当前未登录 重定向到登录页`);
        this.router.navigate(['/passport/login']);
        return false;
    }

    checkMenuAuth(url: string): boolean {
        let ret = (this.checkMenu(this.menu.menus, url));
        if (ret) {
            return true;
        }
        return false;
    }

    checkMenu(ms: Menu[], url: string) {
        for (let menu of ms) {
            if (menu.children.length > 0) {
                let ret = this.checkMenu(menu.children, url);
                if (ret) {
                    return true;
                }
            } else {
                if (url.startsWith(menu.link)) {
                    return true;
                }
            }
        }
    }

    checkLock() {
        if (sessionStorage.getItem(this.cnt.lockFlag) === this.cnt.YES) {
            console.log('当前用户锁定');
            this.router.navigate(['/lock']);
            return false;
        }
        return true;
    }
}
